package com.hup.joystick.view.customView;

import com.hup.utils.commons.exception.AppExceptionHandler;
import com.hup.utils.commons.start.DialogHelper;
import com.hup.utils.swing.ComponentUtil;
import com.hup.utils.swing.customView.ImageButton;
import lombok.extern.log4j.Log4j2;

import javax.swing.*;

/**
 * 设备连接状态view
 *
 * @author hugan
 * @date 2020/10/29
 */
@Log4j2
public class DeviceStateView extends ImageButton {
    private static final ImageIcon ICON_SCANNING = new ImageIcon(DeviceStateView.class.getResource("/img/icon_state_scan.png"));
    private static final ImageIcon ICON_CONNECTED = new ImageIcon(DeviceStateView.class.getResource("/img/icon_state_connected.png"));
    private static final ImageIcon ICON_ERR = new ImageIcon(DeviceStateView.class.getResource("/img/icon_state_err.png"));

    private static final int STATE_SCANNING = 0;
    private static final int STATE_CONNECTED = 1;
    private static final int STATE_ERR = 2;
    private int state = -1;
    private Throwable err;

    public DeviceStateView() {
        setPadding(2);
        setUseSharedIcon(true);
        onScanning();
        setActionListener(e -> {
            if (state == STATE_ERR) {
                log.info("显示错误");
                DialogHelper.show(null, err, ComponentUtil.getParentWindow(DeviceStateView.this));
            } else {
                //无错误,显示tooltip
                DialogHelper.confirm(getToolTipText()).show(ComponentUtil.getParentWindow(DeviceStateView.this));
            }
        });
    }

    public void onScanning() {
        if (state == STATE_SCANNING) return;
        SwingUtilities.invokeLater(() -> {
            state = STATE_SCANNING;
            err = null;
            setIcon(ICON_SCANNING);
            setToolTipText("扫描设备中");
            repaint();
        });
    }

    public void onConnected(String deviceName) {
        if (state == STATE_CONNECTED) return;
        SwingUtilities.invokeLater(() -> {
            state = STATE_CONNECTED;
            err = null;
            setIcon(ICON_CONNECTED);
            setToolTipText("已连接:" + deviceName);
            repaint();
        });

    }

    public void onErr(Throwable e) {
        if (err == e) return;
        AppExceptionHandler.handle(e);
        SwingUtilities.invokeLater(() -> {
            state = STATE_ERR;
            err = e;
            setIcon(ICON_ERR);
            setToolTipText(e.getMessage());
            repaint();
        });

    }

}
